<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8" />
		<title>FIRST</title>
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}
			
			.container {
				width: 100vw;
				height: 100vh;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			
			canvas {
				width: 500px;
				height: 500px;
				border: 10px solid #333333;
			}
		</style>
	</head>

	<body>
		<div class="container">
			<canvas id="canvas" width="500px" height="500px"></canvas>
		</div>
	</body>
	<script>
		window.onload = function() {

			let oCanvas = document.getElementById('canvas');

			console.dir(oCanvas);

			let oPen = oCanvas.getContext("2d");

			this.canvas.onmousedown = function(e) {
				x = e.pageX - oCanvas.offsetLeft;
				y = e.pageY - oCanvas.offsetTop;
				
				document.onmousemove = function(e) {
					var x1 = e.pageX - oCanvas.offsetLeft;
					var y1 = e.pageY - oCanvas.offsetTop;
					
					oPen.lineWidth = 2;
					oPen.strokeStyle = "slateblue"
					oPen.moveTo(x, y)
					oPen.lineTo(x1, y1)
					oPen.stroke();
					x = x1;
					y = y1;
				};
			};

//			document.onmouseout = function(event) {
//				this.onmousemove = null
//			}
			document.onmouseup = function() {
				this.onmousemove = null
			}

            let isMove = false,
                startX=0,
                startY=0;
            
            document.onmousemove = function(e){
            	let nowX = 0;
            	    nowY = 0;
            	    nowX = (e.pageX - oCanvas.offsetLeft);
            	    nowY = (e.pageY - oCanvas.offsetTop);
            	if(isMove){
            		oPen.lineTo(nowX,nowY);
            		oPen.stroke();
            	}
            }
            document.onmousedown = function(e){
            	isMove = true;
            	startX = (e.pageX - oCanvas.offsetLeft);
            	startY = (e.pageY - oCanvas.offsetTop);
            	oPen.moveTo(startX,startY);
            	
            }
            document.onmouseup = function(e){
            	isMove = false;
            }
		}
	</script>

</html>